package com.kk.xhr.admin.util;

import com.kk.xhr.common.ErrorCodeEnum;
import com.kk.xhr.common.exception.BusinessException;
import com.kk.xhr.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件上下传
 *
 * @author kkmystery
 * @version 1.0 2021/3/25
 * @since 1.0.0
 */
@Slf4j
public class FileUtil {
    private static final String CONTEXT = "http://localhost:8080/xhr-backend-mgr/file/";

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件名
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, HttpServletRequest request) {
        // File newFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"img/"+fileId);
        try {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // 文件目录绝对路径
            String filePath = getFilePath();
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 文件唯一标识
            Long fileId = new SnowFlake(1L, 10L).nextId();
            String newFileName = fileId + suffix;
            file.transferTo(new File(dir.getAbsolutePath() + File.separator + newFileName));
            return newFileName;
        } catch (IOException e) {
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAIL);
        }
    }

    public static void download(String fileName, HttpServletResponse response) {
        // 本地文件路径
        String filePath = getFilePath() + File.separator + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(filePath);
        try (//从硬盘中读取数据并上传到前端模板
             //放在()内是需要自动关闭流的
             OutputStream os = response.getOutputStream();
             FileInputStream fis = new FileInputStream(filePath);
        ) {
            response.reset();
            response.setHeader("content-type", "application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            byte[] buffer = new byte[1024];
            int len = 0;
            //将字节流读到缓冲区
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            /*IOUtils.copy(fis, response.getOutputStream());
            response.getOutputStream().flush();*/
        } catch (IOException e) {
           log.error("文件下载失败");
        }
    }

    /**
     * 获取文件目录绝对路径
     *
     * @return 文件目录绝对路径
     */
    public static String getFilePath() {
        // 项目绝对路径
        String prefix = System.getProperty("user.dir").replace("/", "\\");
        return prefix + "\\xhr-backend-mgr\\src\\main\\resources\\static\\file";
    }

    /**
     * 获取文件目录绝对路径
     *
     * @return 文件目录绝对路径
     */
    public static String getTargetFilePath() {
        // 项目绝对路径
        String prefix = System.getProperty("user.dir").replace("/", "\\");
        return prefix + "\\xhr-backend-mgr\\target\\classes\\static\\file";
    }

    /**
     * 获取文件目录绝对路径
     *
     * @return 文件目录绝对路径
     */
    public static String getFileUrl(String fileName) {
        // 项目绝对路径
        return CONTEXT + fileName;
    }
}
